﻿package net.contrend.util;

import java.text.SimpleDateFormat;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;

public class DateConvert implements Converter {

    private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat ymdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat ymdhmsl = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    public DateConvert() {
    }

    @SuppressWarnings("unchecked")
    public Object convert(Class type, Object value) {
        if (value == null) {
            return null;
        }
        if (((String) value).trim().length() == 0) {
            return null;
        }
        if (value instanceof String) {
            try {
                if (((String) value).length() > 19) {
                    return ymdhmsl.parseObject((String) value);
                }
                if (((String) value).indexOf(":") > 0) {
                    return ymdhms.parse((String) value);
                } else {
                    return ymd.parse((String) value);
                }
            } catch (Exception ex) {
                throw new ConversionException("输入的日期类型不合乎yyyy-MM-dd" + value.getClass());
            }
        } else {
            throw new ConversionException("输入的不是字符类型" + value.getClass());
        }
    }

}
